<template>
  <view>
    <z-paging @query="queryList" :refresher-enabled="true" ref="paging" v-model="dataList" class="">
      <view>
        <view v-for="item in dataList" :key="item.id" class="color-bg-fff margin-x-10 margin-y-10 padding-15 border-radius-10 shadow">
          <view class="flex-between margin-bottom-10">
            <view class="font-16 color-333 font-weight">{{ getHeaderName(item) }}</view>
            <view>
              <text class="color-999">开票金额：</text>
              <text class="color-main font-weight font-16">￥{{ item.invoiceAmount }}</text>
            </view>
          </view>
          <view class="flex-between margin-bottom-10">
            <view class="color-666 font-14">
              <text>申请时间：{{ item.createTime }}</text>
            </view>
            <view class="color-666 font-14">
              <text>抬头类型：{{ getHeaderTypeText(item.invoiceHeader.headerType) }}</text>
            </view>
          </view>
          <view class="flex-between margin-bottom-10">
            <view class="color-666 font-14">
              <text>申请人：{{ item.applicantName }}</text>
            </view>
            <view class="color-666 font-14">
              <text>联系电话：{{ item.applicantPhone }}</text>
            </view>
          </view>
          <view v-if="item.invoiceHeader && item.invoiceHeader.headerType === 2" class="margin-bottom-10">
            <view class="color-666 font-14">
              <text>开票人名称：{{ item.invoiceHeader.personalName || '未填写' }}</text>
            </view>
          </view>
          <view v-if="item.invoiceHeader && item.invoiceHeader.headerType === 1" class="margin-bottom-10">
            <view class="color-666 font-14 margin-bottom-5">
              <text>企业名称：{{ item.invoiceHeader.companyName || '未填写' }}</text>
            </view>
            <view class="color-666 font-14">
              <text>公司税号：{{ item.invoiceHeader.taxNumber || '未填写' }}</text>
            </view>
          </view>
          <view class="flex-end margin-top-10">
            <view v-if="item.invoiceStatus === 1">
              <u-button shape="circle" color="#1890FF" :customStyle="{height:'60rpx'}" disabled>处理中</u-button>
            </view>
            <view v-if="item.invoiceStatus === 3">
              <u-button shape="circle" color="#999" :customStyle="{height:'60rpx'}" disabled>已取消</u-button>
            </view>
          </view>
        </view>
      </view>
    </z-paging>
    
    <!-- 空状态 -->
    <view v-if="dataList.length === 0 && !loading" class="empty-state">
      <view class="empty-icon">📄</view>
      <text class="empty-text">暂无开票记录</text>
    </view>
    
    <!-- 开票须知弹窗 -->
    <u-popup :show="showNotice" mode="center" :round="10" width="80%" :safeAreaInsetBottom="false">
      <view class="padding-20">
        <view class="font-16 font-weight color-333 margin-bottom-10">开票须知</view>
        <view class="font-14 color-666">
          1. 请确保填写的发票信息准确无误。<br>
          2. 电子发票将发送至您填写的邮箱。<br>
          3. 如有疑问请联系客服。
        </view>
        <view class="margin-top-20">
          <u-button type="primary" shape="circle" @click="showNotice = false">我知道了</u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { myInvoiceList, cancelInvoice } from '@/api/course/invoice'

export default {
  data() {
    return {
      dataList: [],
      queryParams: {
        pageNo: 1,
        pageSize: 10,
      },
      showNotice: false,
      loading: false
    };
  },
  onLoad() {
    // 页面加载时获取数据
    // this.getList();
  },
  methods: {
    queryList(page) {
      this.queryParams.pageNo = page;
      this.getList();
    },
    async getList() {
      try {
        this.loading = true;
        uni.showLoading({
          title: '加载中...'
        })
        
        const response = await myInvoiceList()
        
        if (response.code === 200) {
          const data = (response.data || []).map(item => ({
            ...item,
            createTime: this.formatDate(item.createTime)
          }))
          this.$refs.paging.complete(data);
        } else {
          this.$refs.paging.complete([]);
          uni.showToast({
            title: response.msg || '获取开票记录失败',
            icon: 'none'
          })
        }
        
      } catch (error) {
        console.error('获取开票记录失败:', error)
        this.$refs.paging.complete([]);
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false;
        uni.hideLoading()
      }
    },
    formatDate(dateStr) {
      if (!dateStr) return '未知时间';
      try {
        const date = new Date(dateStr);
        if (isNaN(date.getTime())) return '未知时间';
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
      } catch (error) {
        return '未知时间';
      }
    },
    getStatusText(status) {
      const statusMap = {
        0: '待处理',
        1: '处理中',
        2: '已完成',
        3: '已取消',
        4: '开票失败'
      };
      return statusMap[status] || '未知状态';
    },
    getStatusClass(status) {
      const classMap = {
        0: 'color-warning',
        1: 'color-primary',
        2: 'color-success',
        3: 'color-999',
        4: 'color-error'
      };
      return classMap[status] || 'color-999';
    },
    getHeaderName(item) {
      if (item.invoiceHeader) {
        if (item.invoiceHeader.headerType === 1) {
          // 企业类型显示企业名称
          return '企业单位：' + item.invoiceHeader.companyName ;
        } else if (item.invoiceHeader.headerType === 2) {
          // 个人类型显示个人名称
          return '个人开票：' + item.invoiceHeader.personalName ;
        }
      }
      // 兜底显示
      return item.companyName || item.personalName || '发票抬头';
    },
    getHeaderTypeText(headerType) {
      if(headerType === 1){
        return '企业单位'
      }else if(headerType === 2){
        return '个人开票'
      }
    },
    cancelInvoice(item) {
      uni.showModal({
        title: '确认取消',
        content: '确定要取消这个开票申请吗？',
        success: (res) => {
          if (res.confirm) {
            this.handleCancelInvoice(item.id);
          }
        }
      });
    },
    async handleCancelInvoice(invoiceId) {
      try {
        uni.showLoading({
          title: '处理中...'
        });
        
        const response = await cancelInvoice(invoiceId);
        
        if (response.code === 200) {
          uni.hideLoading();
          uni.showToast({
            title: '取消成功',
            icon: 'success'
          });
          // 刷新列表
          this.getList();
        } else {
          uni.hideLoading();
          uni.showToast({
            title: response.msg || '取消失败',
            icon: 'none'
          });
        }
        
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: '取消失败，请重试',
          icon: 'none'
        });
      }
    },
    downloadInvoice(item) {
      if (!item.invoiceUrl) {
        uni.showToast({
          title: '发票文件不存在',
          icon: 'none'
        });
        return;
      }
      
      uni.showLoading({
        title: '下载中...'
      });
      
      // 这里处理发票下载逻辑
      setTimeout(() => {
        uni.hideLoading();
        uni.showToast({
          title: '下载成功',
          icon: 'success'
        });
      }, 1000);
    }
  },
};
</script>

<style lang="scss" scoped>
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  
  .empty-icon {
    font-size: 120rpx;
    margin-bottom: 20rpx;
    opacity: 0.5;
  }
  
  .empty-text {
    color: #999;
    font-size: 28rpx;
  }
}

.color-warning {
  color: #FAAD14;
}

.color-primary {
  color: #1890FF;
}

.color-success {
  color: #52C41A;
}

.color-error {
  color: #FF4D4F;
}
</style>

